package com.hncj.android.zxing

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.FragmentActivity
import com.leantech.android.qrcode.core.QRCodeView.Delegate
import com.hncj.android.zxing.databinding.ActivityTestQrcodeBinding
import java.io.InputStream

class TestQRCodeActivity: FragmentActivity(), Delegate {

    companion object{
        fun getBitmapFromUri(context: Context, uri: Uri): Bitmap?{
            var is1: InputStream? = null
            try {
                is1 = context.contentResolver.openInputStream(uri)
                return BitmapFactory.decodeStream(is1)
            } catch (e: Exception) {
                e.printStackTrace()
            } finally {
                is1?.close()
            }
            return null
        }
    }

    private lateinit var binding: ActivityTestQrcodeBinding

    private val pickMedia =
        registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
            binding.zxingview.startSpotAndShowRect()
            if (uri != null) {
                val bm = getBitmapFromUri(this, uri)

                if (bm != null) {
                    binding.zxingview.decodeQRCode(bm)
                }
            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityTestQrcodeBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.zxingview.setDelegate(this)
        binding.zxingview.scanBoxView
        binding.btnPickPhoto.setOnClickListener {
            binding.zxingview.stopSpotAndHiddenRect()
            pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
        }
        binding.btnRescan.setOnClickListener {
            binding.zxingview.startSpot()
            binding.btnRescan.visibility = View.GONE
        }
    }

    override fun onStart() {
        super.onStart()
        binding.zxingview.startCamera()
        binding.zxingview.startSpotAndShowRect()
    }

    override fun onStop() {
        binding.zxingview.stopCamera()
        super.onStop()
    }

    override fun onDestroy() {
        binding.zxingview.onDestroy()
        super.onDestroy()
    }

    override fun onScanQRCodeSuccess(result: String?) {
        if(result.isNullOrBlank()){

        }else{
            Toast.makeText(this, "扫描结果为： ${result}", Toast.LENGTH_SHORT).show()
            binding.btnRescan.visibility = View.VISIBLE
        }
    }

    override fun onCameraAmbientBrightnessChanged(isDark: Boolean) {

    }

    override fun onScanQRCodeOpenCameraError() {

    }
}